package com.wb.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 用于存放Channel的容器
 */
public class ChannelMap<T,V> extends HashMap<T,V>{

    private final Logger logger = LoggerFactory.getLogger(ChannelMap.class);

    private ReentrantLock lock = new ReentrantLock();

    private ChannelMap(){};

    public static ChannelMap instace = new ChannelMap();

    public static ChannelMap getInstance() {
        if (null == instace) {
            instace = new ChannelMap();
        }
        return instace;
    }

    @Override
    public V put(T key, V value) {
        V v = null;
        try {
            lock.lock();
            logger.info("key : {}  , value : {} " , key , value);
            v = super.put(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return v;
    }

    @Override
    public V remove(Object key) {
        V v = null;
        try {
            lock.lock();
            logger.info("key : {} " , key);
            v = super.remove(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return v;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;
        ChannelMap<?, ?> that = (ChannelMap<?, ?>) o;
        return Objects.equals(logger, that.logger) &&
                Objects.equals(lock, that.lock);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), logger, lock);
    }
}